#include "iostream"
#include "vector"
using namespace std;


// Definition for singly - linked list.
struct ListNode
{
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode* func(ListNode* l1, ListNode* l2, int flag)
    {
        ListNode* ans = new ListNode(0, nullptr);

        int a, b;
        a = l1 != nullptr ? l1->val : 0;
        b = l2 != nullptr ? l2->val : 0;
        ans->val = a + b;
        if(flag)
        {
            ans->val++;
        }
        if(ans->val >= 10)
        {
            flag = 1;
            ans->val %= 10;
        }
        else
        {
            flag = 0;
        }

        l1 = l1 != nullptr ? l1->next : 0;
        l2 = l2 != nullptr ? l2->next : 0;
        if(l1 != nullptr || l2 != nullptr || flag)
        {
            ans->next = func(l1, l2, flag);
        }
        return ans;
    }

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        return func(l1, l2, 0);
    }
};
